#include "DB.h"
#include "SQLParser.h"
#include "SQLParserResult.h"
#include "serversocket.h"
#include "buffer.h"
#include "IdxMgr.h"
#include "Dict.h"
#include <string>
#include <iostream>

using namespace std;
using namespace ment;


DB* DB::instance = nullptr;    // 静态成员初始化

DB* DB::getInstance()
{
	if (instance == nullptr)
		instance = new DB();
	return instance;
}

void DB::release()
{
	if (instance != nullptr)
		delete instance;
	instance = nullptr;
}

void DB::init()
{
	Dict::getInstance()->Init();   // 初始化数据字典
	networkServer = new DatabaseServer;  // 创建数据库服务器
}

void DB::run()
{
	networkServer->start();  // 启动数据库服务器
}

void DB::terminate()
{
	cout << "Shutting down database system..." << endl;

	// 保存缓存统计信息到日志文件
	Buffer* buffer = Buffer::getInstance();
	buffer->writeStatsToLogFile("buffer_stats.log");
	buffer->logBufferStats();

	networkServer->stop();        // 关闭数据库服务器
	delete networkServer;					 // 删除网络服务器实例
	Buffer::release();                   // 释放缓冲管理器
	IdxMgr::release();                      // 释放索引管理器
	Dict::release();                        // 释放数据字典

	cout << "Database system has been shut down" << endl;
}